// 数据库操作
const mongoose = require("mongoose");
// 对象规则验证
const Joi = require("joi");

// 模型规则类
const { Schema } = mongoose;

const MappingSchema = new Schema(
  {
    entityName: {
      type: String,
      required: true,
      unique: true,
    },
    storageUri: {
      type: String,
      required: true,
    },
    tableName: {
      type: String,
    },
    idcs: {
      type: Array,
      required: true,
    },
    columns: {
      type: String,
    },
    entity: {
      type: Schema.Types.ObjectId,
      ref: "Entity",
      required: true,
    },
    storage: {
      type: Schema.Types.ObjectId,
      ref: "Storage",
      required: true,
    },
  },
  { versionKey: false }
);

const Mapping = mongoose.model("Mapping", MappingSchema);

// 定义对象验证规则
const mappingRules = {
  entityName: Joi.string().required().error(new Error("entityName 是必需的")),
  storageUri: Joi.string().required().error(new Error("storageUri 是必需的")),
};

// 注册数据格式校验
const validateMapping = (mapping) => {
  return Joi.validate(mapping, mappingRules, {
    // 检测到所有错误
    abortEarly: false,
    // 允许对象包含被忽略的未知键
    allowUnknown: true,
  });
};

// 导出对象
module.exports = {
  Mapping,
  mappingRules,
  validateMapping,
};
